import React, { useState, useMemo, useEffect } from "react";
import { Canvas } from "@react-three/fiber";
import ThreDCom from "./components/3DCom";
import * as THREE from "three";
import img from "../../assets/images/3.jpg";

const ROOM_SIZE = 80; // 房间基础尺寸
const WALL_HEIGHT = 15; // 墙面高度
const WALL_THICKNESS = 0.3; // 墙体厚度

type WallMaterials = {
  mainWall: THREE.MeshStandardMaterial;
  partition: THREE.MeshStandardMaterial;
  trim: THREE.MeshStandardMaterial;
  floor: THREE.MeshStandardMaterial;
  photo: THREE.MeshStandardMaterial;
};

const Display: React.FC = () => {
  const [isMouseLocked, setIsMouseLocked] = useState(false);

  // 预加载纹理和材质
  const materials = useMemo<WallMaterials>(() => {
    const textureLoader = new THREE.TextureLoader();
    return {
      mainWall: new THREE.MeshStandardMaterial({
        color: "#f5f5f0",
        roughness: 0.3,
        metalness: 0.1
      }),
      partition: new THREE.MeshStandardMaterial({
        color: "#e8e0d8",
        roughness: 0.4,
        metalness: 0
      }),
      trim: new THREE.MeshStandardMaterial({
        color: "#d4af37",
        roughness: 0.2,
        metalness: 0.7
      }),
      floor: new THREE.MeshStandardMaterial({
        color: "#f0f6fa",
        roughness: 0.5,
        metalness: 0.1
      }),
      photo: new THREE.MeshStandardMaterial({
        map: textureLoader.load(img),
        metalness: 0,
        roughness: 0.8,
        transparent: true
      })
    };
  }, []);

  // 创建基础墙体
  const createWall = (
    position: [number, number, number],
    rotation: number,
    length: number
  ) => (
    <mesh
      position={position}
      rotation={[0, rotation, 0]}
      castShadow
      receiveShadow
    >
      <boxGeometry args={[length, WALL_HEIGHT, WALL_THICKNESS]} />
      <primitive object={materials.mainWall} />
      <mesh position={[0, -6, 0]}>
        <boxGeometry args={[length, 0.1, WALL_THICKNESS]} />
        <primitive object={materials.trim} />
      </mesh>
    </mesh>
  );

  // 创建隔断墙
  const createPartition = (
    position: [number, number, number],
    rotation: number,
    length: number
  ) => (
    <group position={position} rotation={[0, rotation, 0]}>
      <mesh receiveShadow>
        <boxGeometry args={[length, WALL_HEIGHT, WALL_THICKNESS]} />
        <primitive object={materials.partition} />
      </mesh>
      <mesh position={[0, -6, 0]}>
        <boxGeometry args={[length, 0.1, WALL_THICKNESS]} />
        <primitive object={materials.trim} />
      </mesh>
    </group>
  );

  // 创建相框
  const createPhotoFrame = (
    position: [number, number, number],
    rotation: number,
    size: [number, number]
  ) => (
    <group position={position} rotation={[0, rotation, 0]}>
      <mesh position={[0, 1, 0.1]}>
        <boxGeometry args={[size[0], size[1], 0.2]} />
        <meshStandardMaterial color="#3e2e1d" roughness={0.4} />
      </mesh>
      <mesh position={[0, 1, 0.15]}>
        <planeGeometry args={[size[0]-0.2, size[1]-0.2]} />
        <primitive object={materials.photo} />
      </mesh>
    </group>
  );

  useEffect(() => {
    const handlePointerLockChange = () => {
      setIsMouseLocked(!!document.pointerLockElement);
    };
    document.addEventListener("pointerlockchange", handlePointerLockChange);
    return () => document.removeEventListener("pointerlockchange", handlePointerLockChange);
  }, []);

  return (
    <div
      style={{ width: "200%", height: "165vh",
        
         cursor: isMouseLocked ? "none" : "pointer" }}
      onClick={() => !isMouseLocked && document.body.requestPointerLock()}
    >
      <Canvas shadows camera={{ fov: 75, near: 0.1, far: 1000 }}>
        <ThreDCom
          initialPosition={[0, 4, 0]}
          moveSpeed={0.3}
          mouseSensitivity={0.002}
          isActive={isMouseLocked}
          roomSize={ROOM_SIZE}
        />

        {/* 光照系统 */}
        <ambientLight intensity={0.6} />
        <directionalLight
          position={[40, 50, 40]}
          intensity={1.5}
          castShadow
          shadow-mapSize={[4096, 4096]}
        />
        <hemisphereLight intensity={0.3} groundColor="#888888" />

        {/* 地面 */}
        <mesh rotation={[-Math.PI / 2, 0, 0]} receiveShadow>
          <planeGeometry args={[ROOM_SIZE * 2, ROOM_SIZE * 2]} />
          <primitive object={materials.floor} />
        </mesh>

        {/* 外墙系统 */}
        {createWall([0, WALL_HEIGHT/2, -ROOM_SIZE], 0, ROOM_SIZE*2)} {/* 后墙 */}
        {createWall([0, WALL_HEIGHT/2, ROOM_SIZE], 0, ROOM_SIZE*2)}  {/* 前墙 */}
        {createWall([-ROOM_SIZE, WALL_HEIGHT/2, 0], Math.PI/2, ROOM_SIZE*2)} {/* 左墙 */}
        {createWall([ROOM_SIZE, WALL_HEIGHT/2, 0], Math.PI/2, ROOM_SIZE*2)}  {/* 右墙 */}

        {/* 隔断系统 - 三室一厅布局 */}
        {createPartition([-ROOM_SIZE/2, WALL_HEIGHT/2, 0], Math.PI/2, ROOM_SIZE)} {/* 左卧室 */}
        {createPartition([ROOM_SIZE/2, WALL_HEIGHT/2, 0], -Math.PI/2, ROOM_SIZE)} {/* 右卧室 */}
        {createPartition([0, WALL_HEIGHT/2, ROOM_SIZE/2], 0, ROOM_SIZE)} {/* 客厅隔断 */}

        {/* 相框装饰 */}
        {createPhotoFrame([-ROOM_SIZE+4, 0, -ROOM_SIZE+0.1], 0, [5, 3])} {/* 主卧室 */}
        {createPhotoFrame([ROOM_SIZE-4, 0, -ROOM_SIZE+0.1], Math.PI, [5, 3])} {/* 次卧室 */}
        {createPhotoFrame([0, 0, ROOM_SIZE-0.1], Math.PI, [6, 4])} {/* 客厅 */}

        {/* 天花板 */}
        <mesh position={[0, WALL_HEIGHT, 0]} rotation={[Math.PI/2, 0, 0]} receiveShadow>
          <planeGeometry args={[ROOM_SIZE*2, ROOM_SIZE*2]} />
          <meshStandardMaterial color="#e0e0e0" roughness={0.6} />
        </mesh>
      </Canvas>

      {!isMouseLocked && (
        <div style={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
          color: "white",
          textAlign: "center",
          backgroundColor: "rgba(0,0,0,0.7)",
          padding: "20px",
          borderRadius: "10px",
          fontSize: "1.2em"
        }}>
          <div>点击任意位置开始探索</div>
          <div style={{ fontSize: "0.8em", marginTop: "10px", color: "#ccc" }}>
            WASD移动 | 鼠标控制视角<br/>
            空格跳跃 | ESC退出
          </div>
        </div>
      )}
    </div>
  );
};

export default Display;